package com.weilive.platform.gate.json.handler;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.weilive.core.netty.NettyErrors;
import com.weilive.core.protocol.json.JsonRequest;
import com.weilive.core.protocol.json.JsonRequestHandler;
import com.weilive.core.protocol.json.JsonResponse;
import com.weilive.core.utils.MD5Utils;
import com.weilive.core.utils.RSAUtils;
import com.weilive.core.utils.RegexUtils;
import com.weilive.core.utils.StringUtils;
import com.weilive.platform.PlatformErrors;
import com.weilive.platform.PlatformSecurity;
import com.weilive.platform.cache.app.AppManager;
import com.weilive.platform.cache.app.AppObj;
import com.weilive.platform.cache.user.UserManager;
import com.weilive.platform.cache.user.UserObj;
import com.weilive.platform.gate.json.protocol.CSA_PlatUserLogin;
import com.weilive.platform.gate.json.protocol.CSQ_PlatUserLogin;
import com.weilive.platform.third.ThirdPlatSDK.ThirdCheck;
import com.weilive.platform.third.ThirdSDKManager;

/**
 * 平台用户登陆
 * 
 * @author houge
 * 
 */
@Service
public class CSQ_PlatUserLogin_JsonHandler extends JsonRequestHandler {

	public Class<?> getRequestType() {
		return CSQ_PlatUserLogin.class;
	}

	public Class<?> getResponseType() {
		return CSA_PlatUserLogin.class;
	}

	public JsonResponse handleRequest(JsonRequest request) throws Exception {
		CSQ_PlatUserLogin params = (CSQ_PlatUserLogin) request.getData();

		if (params.app_id == null || params.client_id == null || params.cluster_id == null) {
			return createErrorResponse(NettyErrors.BAD_REQUEST);
		}
		// 游戏检测
		AppObj app = AppManager.getApp(params.app_id);
		if (app == null) {
			return createErrorResponse(PlatformErrors.APP_NOT_EXIST);
		}

		UserObj user = null;
		ThirdCheck thridCheck = null;
		/* 账号登录检测 */
		if ((params.account != null || params.email != null || params.phone != null) && params.password != null) {
			String password = PlatformSecurity.hexStringServerDecrypt(params.password);
			if (params.account != null) {
				if (RegexUtils.isAccount(params.account) == false) {
					return createErrorResponse(PlatformErrors.INVALID_ACCOUNT);
				}
				user = UserManager.getUserByAccount(params.account);
			} else if (params.email != null) {
				if (RegexUtils.isEmail(params.email) == false) {
					return createErrorResponse(PlatformErrors.INVALID_EMAIL);
				}
				user = UserManager.getUserByEmail(params.email);
			} else {
				if (RegexUtils.isPhone(params.phone) == false) {
					return createErrorResponse(PlatformErrors.INVALID_PHONE);
				}
				user = UserManager.getUserByPhone(params.phone);
			}
			if (user != null && MD5Utils.encryptToHex(password).equals(user.info.password) == false) {
				return createErrorResponse(PlatformErrors.WRONG_PASSWORD);
			}
			/* 设备登录检测(游客) */
		} else if (params.device != null && params.device_id != null) {
			String device_id = params.device_id;
			;
			String device_uid = UserManager.getDeviceUid(params.device, device_id);
			user = UserManager.getUserByDeviceUid(device_uid);
			if (user == null) {
				user = UserManager.createUserByDevice("g" + params.app_id, params.device, device_uid);
			}
			/* 第三方渠道登录检测 */
		} else if (params.channel != null && params.channel_uid != null && params.channel_token != null) {
			String channel_token = PlatformSecurity.hexStringServerDecrypt(params.channel_token);
			// 第三方登陆返回,不为null表示成功
			thridCheck = ThirdSDKManager.checkUserLogin(params.app_id, params.channel, params.channel_uid,
					channel_token, params.channel_attach);
			if (thridCheck != null && !StringUtils.isNull(thridCheck.userId)) {
				String channel_uid = UserManager.getChannelUid(params.channel, thridCheck.userId);
				user = UserManager.getUserByChannelUid(channel_uid);
				if (user == null) {
					user = UserManager.createUserByChannel("g" + params.app_id, params.channel, channel_uid);
				}
			} else {
				return createErrorResponse(PlatformErrors.THIRD_INVALID_CHECK);
			}
		} else {
			return createErrorResponse(NettyErrors.BAD_REQUEST);
		}
		if (user == null) {
			return createErrorResponse(PlatformErrors.USER_NOT_EXIST);
		}

		// 返回
		CSA_PlatUserLogin response = new CSA_PlatUserLogin();
		response.uin = UserManager.getUin(user.info.user_id);
		response.token = user.updateToken(params.app_id);
		response.date = System.currentTimeMillis();
		response.account = user.info.account;
		response.email = user.info.email;
		response.phone = user.info.phone;

		if (thridCheck != null) {
			response.channel_uid = thridCheck.userId;
			response.channel_token = thridCheck.userToken;
		}
		return JsonResponse.create(response);
	}

	public static void main(String[] args) throws Exception {
		List<String> params = new ArrayList<String>();

		String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLvSku3ZeWL50q+s4Qh/3ANzIQ9T6m4LgN7y1OlY69dJ"
				+ "YhE7olVuBxuY0NBrR/wozJaO6mkJSYqWcGfs6qxAy9Vrt8UOwtVNHHmc6Sp+P08q5hdx56RaA5DSQFS3cyRgNMl1yPmbppllKv14w1wjijaU8hR+POAWgSZXdK7Ao/pQIDAQAB";

		String key1 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLvSku3ZeWL50q+s4Qh/3ANzIQ9T6m4LgN7y1OlY69dJYhE7olVuBxuY0NBrR/wozJ";
		String key2 = "aO6mkJSYqWcGfs6qxAy9Vrt8UOwtVNHHmc6Sp+P08q5hdx56RaA5DSQFS3cyRgNMl1yPmbppllKv14w1wjijaU8hR+POAWgSZXdK7Ao/pQIDAQAB";

		params.add(PlatformSecurity.base64ClientEncrypt(key1));
		params.add(PlatformSecurity.base64ClientEncrypt(key2));
		// 读取客户端公钥
		String pub_key = "";
		if (params != null && params.size() == 2) {
			for (String key : params) {
				String data = PlatformSecurity.base64ServerDecrypt(key);
				if (data != null) {
					pub_key += data;
				} else {
					pub_key = null;
					break;
				}
			}
		}
		System.out.println(pub_key);
		System.out.println(pub_key.equals(publicKey));

		String str = "abddddddddddddddssss";
		String encryStr = RSAUtils.base64EncryptByPublicKey(str, pub_key);

		System.out.println(encryStr);

		// String decryStr = RSAUtils.base64DecryptByPublicKey(encryStr,
		// pub_key);

		String decryStr = PlatformSecurity.base64ServerDecrypt(encryStr);

		System.out.println(decryStr);
	}

}
